import axios from 'axios'
import store from '@/store'
import { getToken, getCallbackUrl } from '@/utils/auth'
import qs from 'qs'
import router from '@/router'
import config from '@/config/request.config'
import Cookies from 'js-cookie'

const ERROR_ALERT_COUNT_401 = 'unicom_mall3.0_erroralert_401'
const globals = config()
// create an axios instance
const service = axios.create({
  // baseURL: globals.gatewayUrl, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
})
const showErrorMsg = function(msg, resp) {
  if (resp && resp.data && resp.data.message) {
    msg = resp.data.message
  }
  window.vm.$message({
    message: msg,
    type: 'error',
    showClose: true
  })
}
const show401Msg = function(msg, isLogin) {
  if (!Cookies.get(ERROR_ALERT_COUNT_401)) {
    Cookies.set(ERROR_ALERT_COUNT_401, 'have')
    window.vm.$msgbox({
      title: '错误提示',
      message: msg,
      type: 'error',
      callback: () => {
        Cookies.remove(ERROR_ALERT_COUNT_401)
      }
    })
  }
}
// 401错误处理器
const error401Handle = function(error, msg) {
  const isLogin = error.config.url.indexOf('login') >= 0
  if (isLogin) {
    msg = error.response.data
    return Promise.reject(new Error(msg))
  }
  if (error.response.status === 401) {
    if (error.response.data) {
      msg = error.response.data
    }
    show401Msg(msg, isLogin)
    // 401表示token无效或未登录或超时，此时需要清空token
    const callback = getCallbackUrl()
    store.dispatch('user/resetToken')
    if (callback) {
      window.location.href = callback
      window.location.reload()
    } else {
      router.push('/login')
    }
    return Promise.reject(error)
  }
}
// request interceptor
service.interceptors.request.use(
  config => {
    if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    // if (response.status !== 200) {
    //   window.vm.$message({
    //     message: res.message || 'Error',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })
    //
    //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //     // to re-login
    //     window.vm.$confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
    //       confirmButtonText: 'Re-Login',
    //       cancelButtonText: 'Cancel',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('user/resetToken').then(() => {
    //         location.reload()
    //       })
    //     })
    //   }
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else if (res.hasOwnProperty('success') && !res.success) {
      // window.vm.$message({
      //   message: res.msg || '服务器异常！',
      //   type: 'error',
      //   duration: 5 * 1000
      // })
      // window.vm.$msgSuccess(res.msg || '服务器异常！', 'error')
      return res
    // } else {
    //   return res
    // }
  },
  error => {
    // if (!error.response) {
    //   const callback = getCallbackUrl()
    //   store.dispatch('user/resetToken')
    //   if (callback) {
    //     window.location.href = callback
    //     window.location.reload()
    //   } else {
    //     router.push('/login')
    //     window.location.reload()
    //   }
    //   return Promise.reject(error)
    // }
    // const newJwtToken = error.response.headers.jwttoken
    // if (newJwtToken) {
    //   store.dispatch('user/login', { 'token': newJwtToken })
    // }
    // const autoMsg = error.response.config.autoMsg
    // if (error.response.status !== 401 && autoMsg === false) {
    //   return Promise.reject(error)
    // }
    // if (error.response.status === 406) {
    //   // 自定义错误
    //   showErrorMsg(error.response.data.message, error.response)
    //   return Promise.reject(error)
    // }
    // let msg = '未知错误,我们已将错误信息发送给管理员,请耐心等待解决!'
    // switch (error.response.status) {
    //   case 500:
    //     msg = '后台执行出错,我们已将错误信息发送给管理员,请耐心等待解决!'
    //     showErrorMsg(msg, error.response)
    //     break
    //   case 404:
    //     msg = '你访问的地址不存在,我们已将错误信息发送给管理员,请耐心等待解决!'
    //     showErrorMsg(msg, error.response)
    //     break
    //   case 403:
    //     msg = '你无权限访问此接口!继续访问将对你的账号带来灾难性后果!'
    //     showErrorMsg(msg, error.response)
    //     break
    //   case 401:
    //     return error401Handle(error, msg)
    //     break
    //   default:
    //     showErrorMsg(msg)
    //     break
    // }
    return Promise.reject(error)
  }
)

export { service, globals }

export default service
